package com.example.utility.crypto.sha;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 季舟
 * @Date 2025-01-02 14:12
 */
public class SHADemo {
    /**
     * 使用指定的算法生成输入字符串的SHA哈希值
     *
     * @param algorithm 哈希算法名称，例如"SHA-256"
     * @param input 需要生成哈希值的输入字符串
     * @return 使用指定算法生成的哈希值的十六进制字符串表示
     * @throws RuntimeException 如果指定的哈希算法不可用，则抛出运行时异常
     */
    public static String generateSHA(String algorithm,String input) {
        try {
            // 获取指定算法的MessageDigest实例
            MessageDigest digest = MessageDigest.getInstance(algorithm);

            // 将输入字符串转换为字节数组并计算哈希值
            byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            // 返回十六进制字符串表示的哈希值
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            // 如果指定的哈希算法不可用，抛出运行时异常
            throw new RuntimeException(algorithm + " algorithm not found", e);
        }
    }

    /**
     * 主程序入口
     * 演示如何使用generateSHA函数生成不同SHA变种的哈希值
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        // 示例输入字符串
        String input = "Hello, SHA!";
        System.out.println("输入: " + input);

        // 遍历不同的SHA算法，生成并打印哈希值
        String algorithm = "SHA-224";
        System.out.println("算法"+algorithm+"的哈希值: " + generateSHA(algorithm,input));
        algorithm = "SHA-256";
        System.out.println("算法"+algorithm+"的哈希值: " + generateSHA(algorithm,input));
        algorithm = "SHA-384";
        System.out.println("算法"+algorithm+"的哈希值: " + generateSHA(algorithm,input));
        algorithm = "SHA-512";
        System.out.println("算法"+algorithm+"的哈希值: " + generateSHA(algorithm,input));
        algorithm = "SHA-512/224";
        System.out.println("算法"+algorithm+"的哈希值: " + generateSHA(algorithm,input));
        algorithm = "SHA-512/256";
        System.out.println("算法"+algorithm+"的哈希值: " + generateSHA(algorithm,input));
    }
}

